import RateItem from "./Item";
import createField from "../../use/createField";
import { PropType, computed, defineComponent, ref } from "vue";

export interface RateProps {
    disabled?: boolean,
    icon: any,
    modelValue?: number,
    count?: number,
    allowHalf?: boolean,
    onChange?: (val: number) => void,
    name?: string
    asFormField?: boolean
}

export default defineComponent({
    name: 'Rate',
    props: {
        disabled: { type: Boolean as PropType<RateProps['disabled']>},
        icon: { type: Object as PropType<RateProps['icon']>},
        modelValue: { type: Number as PropType<RateProps['modelValue']>},
        count: { type: Number as PropType<RateProps['count']>},
        allowHalf: { type: Boolean as PropType<RateProps['allowHalf']>},
        name: { type: String as PropType<RateProps['name']>},
        asFormField: { type: Boolean as PropType<RateProps['asFormField']>, default: true }
    },
    emits: ['change', 'update:modelValue'],
    setup (props, { emit, slots }) {
        const classList = computed(() => ({
            'cm-rate': true,
            'cm-rate-disabled': props.disabled
        }));
        if (!props.icon || slots.icon) {
            console.warn('need icon slot or property');
            return null;
        }
        const value = createField(props, emit);
        const current = ref(value.value);
        const allowHalf = props.allowHalf || false;

        const onMouseEnter = (val: number) => {
            current.value = val;
        };

        const onMouseEnterHalf = (val: number, e: any) => {
            if (!allowHalf) {
                return;
            }
            e.preventDefault();
            e.stopPropagation();
            current.value = val;
        };

        const onMouseLeave = () => {
            current.value = value.value;
        };

        const onClickStar = (val: number) => {
            value.value = val;
            emit('change', val);
        };

        const onClickHalfStar = (val: number, e: any) => {
            e.preventDefault();
            e.stopPropagation();
            if (!allowHalf) {
                return;
            }
            value.value = val;
            emit('change', val);
        };

        const count = props.count || 5;
        const stars = [];
        for (let i = 0; i < count; i++) {
            stars.push({id: i, value: i});
        }

        return () => <div class={classList.value} onMouseleave={onMouseLeave}>
            {
                stars.map((item, index) => {
                    return <RateItem index={index} onMouseEnterHalf={onMouseEnterHalf} onClickHalfStar={onClickHalfStar}
                        onMouseEnter={onMouseEnter} onClickStar={onClickStar} icon={props.icon || slots.icon?.()} allowHalf={allowHalf}
                        current={current.value}/>;
                })
            }
            <span>{slots.default?.()}</span>
        </div>;
    }
});
